package com.kevin.util.tag;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class StringSubTag  extends TagSupport{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 134546456L;
	private String content;
	private int size;
	private boolean suf = true;
	

	

	public String getContent() {
		return content;
	}

	public void setContent(String content) {
		this.content = content;
	}

	

	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}
	

	public boolean isSuf() {
		return suf;
	}

	public void setSuf(boolean suf) {
		this.suf = suf;
	}

	@Override
	public int doEndTag() throws JspException {
		// TODO Auto-generated method stub
		content = content.trim();
		content=replaceHtml(content);
		try {	
			int totalCount = 0;
			String newStr = "";
			for (int i=0; i<content.length(); i++) {  
		         char c = content.charAt(i);  
		         if ((c >= 0x0001 && c <= 0x007e) || (0xff60<=c && c<=0xff9f)) {  
		             totalCount++;  
		         }else {     
		             totalCount+=2;  
		         }  
		         if(totalCount <= size){ 
		             newStr = content.substring(0,i+1); 
		         }else{ 
		        	 if(suf)
		        		 newStr += "..."; 
		        	 else; 
		             break;
		         } 
		     } 
			pageContext.getOut().print(newStr);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return SKIP_BODY;
	}

	@Override
	public int doStartTag() throws JspException {
		// TODO Auto-generated method stub
		return EVAL_PAGE;
	}
	/**
	 * 去html标签
	 * @param html
	 * @return
	 */
	private String replaceHtml(String html){   
        String regEx="<\\/?[^>]+>"; //表示标签   
        Pattern p=Pattern.compile(regEx);   
        Matcher m=p.matcher(html);   
        String s=m.replaceAll("");   
        return s;   
    } 
//	public static void main(String[] args) {
//		StringSub ss = new StringSub();
//		String htmlStr = "<a href='a'>sfesd</a>==sdfwewr<p>+dsfe</p>";
//	}

}
